import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easylogger/flutter_logger.dart';

import '../../../../http/http_service.dart';
import '../../../../models/order_model.dart';
import '../../../../utils/user_info_utils.dart';

class OrderManagementLogic extends GetxController {
  // 订单列表
  final orders = <Order>[].obs;

  // 加载状态
  final isLoading = false.obs;

  // 展开的订单ID
  final expandedOrderId = RxnInt();

  // 主题颜色
  final Color primaryColor = Color(0xFFBE9650);
  final Color lightColor = Color(0xFFE6E6FA);

  // HTTP服务
  final httpService = HttpService();

  @override
  void onInit() {
    super.onInit();
    loadOrders();
  }

  // 加载订单列表
  Future<void> loadOrders() async {
    // 获取用户ID
    var loginModel = DataUtils().getLoginModel();
    var userId = loginModel.id;

    if (userId == null) {
      Logger.e('未获取到用户ID，无法加载订单');
      Get.snackbar(
        '加载失败',
        '未获取到用户信息，请重新登录',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white70,
      );
      return;
    }

    if (isLoading.value) return;

    isLoading.value = true;
    Logger.d('开始加载订单列表，用户ID: $userId');

    try {
      final response = await httpService.get('/orders', queryParameters: {'userId': userId});

      if (response.statusCode == 200) {
        // 解析订单数据
        final List<dynamic> ordersData = response.data;
        orders.clear();

        orders.addAll(ordersData.map((data) {
          // 解析订单项
          final List<dynamic> itemsData = data['items'] ?? [];
          final List<OrderItem> items = itemsData.map((item) => OrderItem(
            id: item['id'],
            foodId: item['foodId'],
            foodName: item['foodName'],
            foodImage: item['foodImage'],
            quantity: item['quantity'],
            price: double.parse(item['price'].toString()),
          )).toList();

          return Order(
            id: data['id'],
            userId: data['userId'],
            username: data['username'] ?? '',
            totalPrice: double.parse(data['totalPrice'].toString()),
            address: data['address'],
            addressDetail: data['addressDetail'],
            remark: data['remark'] ?? '',
            status: data['status'],
            createdAt: DateTime.parse(data['createdAt']),
            updatedAt: DateTime.parse(data['updatedAt']),
            items: items,
          );
        }));

        Logger.i('订单加载成功，共 ${orders.length} 个订单');
      } else {
        Logger.e('订单加载失败: ${response.statusCode}');
        Get.snackbar(
          '加载失败',
          '订单数据加载失败，请重试',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.white70,
        );
      }
    } catch (e) {
      Logger.e('订单加载异常: $e');
      Get.snackbar(
        '加载失败',
        '订单数据加载失败，请检查网络连接',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white70,
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 切换订单展开状态
  void toggleOrderExpanded(int orderId) {
    if (expandedOrderId.value == orderId) {
      expandedOrderId.value = null;
    } else {
      expandedOrderId.value = orderId;
    }
  }

  // 获取订单状态颜色
  Color getStatusColor(String status) {
    switch (status) {
      case 'PENDING':
        return Colors.orange;
      case 'PAID':
        return Colors.blue;
      case 'PREPARING':
        return Colors.purple;
      case 'DELIVERING':
        return Colors.indigo;
      case 'COMPLETED':
        return Colors.green;
      case 'CANCELLED':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  // 获取订单状态文本
  String getStatusText(String status) {
    switch (status) {
      case 'PENDING':
        return '待付款';
      case 'PAID':
        return '已付款';
      case 'PREPARING':
        return '准备中';
      case 'DELIVERING':
        return '配送中';
      case 'COMPLETED':
        return '已完成';
      case 'CANCELLED':
        return '已取消';
      default:
        return '未知状态';
    }
  }

  // 更新订单状态
  Future<void> updateOrderStatus(Order order, String newStatus) async {
    // 获取用户ID
    var loginModel = DataUtils().getLoginModel();
    var userId = loginModel.id;

    if (userId == null) {
      Logger.e('未获取到用户ID，无法更新订单状态');
      Get.snackbar(
        '操作失败',
        '未获取到用户信息，请重新登录',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white70,
      );
      return;
    }

    try {
      final response = await httpService.post(
        '/orders/${order.id}/status',
        data: {
          'userId': userId,
          'status': newStatus,
        },
      );

      if (response.statusCode == 200) {
        Logger.i('订单状态更新成功: ${order.id} -> $newStatus');
        Get.snackbar(
          '成功',
          '订单状态已更新',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green.withOpacity(0.8),
          colorText: Colors.white,
        );
        
        // 重新加载订单列表
        await loadOrders();
      } else {
        Logger.e('订单状态更新失败: ${response.statusCode}');
        Get.snackbar(
          '更新失败',
          '订单状态更新失败，请重试',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red.withOpacity(0.8),
          colorText: Colors.white,
        );
      }
    } catch (e) {
      Logger.e('订单状态更新异常: $e');
      Get.snackbar(
        '更新失败',
        '订单状态更新失败: ${e.toString()}',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
    }
  }

  // 完成订单
  Future<void> completeOrder(Order order) async {
    // 获取用户ID
    var loginModel = DataUtils().getLoginModel();
    var userId = loginModel.id;

    if (userId == null) {
      Logger.e('未获取到用户ID，无法完成订单');
      Get.snackbar(
        '操作失败',
        '未获取到用户信息，请重新登录',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white70,
      );
      return;
    }

    try {
      final response = await httpService.post(
        '/orders/${order.id}/complete',
        queryParameters: {'userId': userId},
      );

      if (response.statusCode == 200) {
        Logger.i('订单完成成功: ${order.id}');
        Get.snackbar(
          '成功',
          '订单已标记为完成',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green.withOpacity(0.8),
          colorText: Colors.white,
        );
        
        // 重新加载订单列表
        await loadOrders();
      } else {
        Logger.e('订单完成失败: ${response.statusCode}');
        Get.snackbar(
          '操作失败',
          '订单完成失败，请重试',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red.withOpacity(0.8),
          colorText: Colors.white,
        );
      }
    } catch (e) {
      Logger.e('订单完成异常: $e');
      Get.snackbar(
        '操作失败',
        '订单完成失败: ${e.toString()}',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
    }
  }
}
